package com.forester.foresterplatform.common.utils;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 封装MyBatisPlus再使用过程当中需要的常用功能
 */
public class MyBatisPlusUtils {

    /**
     * 解析形如 'name asc, age desc' 的字符串为 com.baomidou.mybatisplus.core.metadata.OrderItem 列表
     * @param sortString
     * @return
     */
    public static List<OrderItem> parseSort(String sortString) {
        List<OrderItem> res = new ArrayList<>();
        sortString = sortString.trim();
        if(!StringUtils.hasText(sortString))
            return res;

        String[] sortArray = Arrays.stream(sortString.split(",")).map(String::trim).toArray(String[]::new);
        for (int i = 0; i < sortArray.length; i++) {

            OrderItem orderItem = new OrderItem();
            String[] s = Arrays.stream(sortArray[i].split(" ")).map(String::trim).toArray(String[]::new);
            if(s.length > 2)
                throw new RuntimeException("排序字符串格式错误");

            // column
            orderItem.setColumn(s[0]);

            // asc/desc
            if(s.length > 1) {
                if("asc".equalsIgnoreCase(s[1]))
                    orderItem.setAsc(true);
                else if("desc".equalsIgnoreCase(s[1]))
                    orderItem.setAsc(false);
                else
                    throw new RuntimeException("排序字符串格式错误");
            }
            res.add(orderItem);
        }
        return res;
    }
}
